/**
 * 数据操作文件模块
 */
const { response } = require('express')
var fs = require('fs')
var dbPath = './db.json'
/**
 * 获取所有学生
 */
exports.find = function (callback) {
    fs.readFile(dbPath, 'utf8', function (err, data) {       
        if(err){
            return callback(err)
        }
        callback(null, JSON.parse(data).students)
    })
}

/**
 * 根据id获取学生
 * @param {*} id 
 * @param {*} callback 
 */
exports.findById = function (id, callback) {
    fs.readFile(dbPath, 'utf8', function (err, data) {
        if (err) {
            return callback(err)
        }
        var students = JSON.parse(data).students
        var ret = students.find(function (item) {
            return item.id == id
        })
        callback(null, ret)
    })
}


/**
 * 添加保存学生
 */
exports.save = function (student, callback) {
    fs.readFile(dbPath, 'utf8', function (err, data){
        if(err){
            return callback(err)
        } 
        var stuendts = JSON.parse(data).students
        if (stuendts == 'undefined' || stuendts == ''){
            student.id = 1
        }else{
            student.id = stuendts[stuendts.length - 1].id + 1
        }
        stuendts.push(student)
        var fileData = JSON.stringify({
            students: stuendts
        })
        fs.writeFile(dbPath, fileData, function (err) {
            if(err){
                return callback(err)
            }
            callback(null)
        })
    })
}

/**
 * 更新学生
 */
exports.update = function (student, callback) {
    fs.readFile(dbPath, 'utf8', function (err, data){
        if(err){
            return callback(err)
        }
        var students = JSON.parse(data).students

        student.id = parseInt(student.id)
        var stu = students.find(function (item) {
            return item.id == student.id
        })
        for(var key in student){
            stu[key] = student[key]
        }

        var fileData = JSON.stringify({
            students: students
        })

        fs.writeFile(dbPath, fileData, function(err, data) {
            if (err){
                return callback(err)
            }
            callback(null)
        })

    })
}

/**
 * 删除学生
 */
exports.delete = function (id, callback) {
    fs.readFile(dbPath, 'utf8', function (err, data) {
        if (err) {
            return callback(err)
        }
        var students = JSON.parse(data).students

        var delId = students.findIndex(function(item){
            return item.id === id
        })

        students.splice(delId,1)

        var fileData = JSON.stringify({
            students: students
        })

        fs.writeFile(dbPath, fileData, function(err){
            if(err){
                return callback(err)
            }
            callback(null)
        })

    })
}